package com.oc.claimobs.bb.screens;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import ar.com.lemil.bb.http.commands.CommandCallback;
import ar.com.lemil.bb.utils.log.ILogger;
import ar.com.lemil.bb.utils.log.Logger;

import com.oc.claimobs.bb.ScreenFlow;
import com.oc.claimobs.bb.commands.SendReclamoCommand;
import com.oc.claimobs.bb.facade.InfoService;
import com.oc.claimobs.bb.model.Info;
import com.oc.utils.Style;

public class SendingScreen extends MainScreen implements ILogger,CommandCallback {
	protected static final Runnable Runnable = null;
	private Bitmap backgroundBitmap;

	public SendingScreen() {
	//	super(MainScreen.NO_VERTICAL_SCROLL | MainScreen.NON_FOCUSABLE
	//			| MainScreen.NO_HORIZONTAL_SCROLL
	//			| MainScreen.NO_VERTICAL_SCROLLBAR
	//			| MainScreen.NO_HORIZONTAL_SCROLLBAR);

		super(MainScreen.NON_FOCUSABLE
				| MainScreen.NO_HORIZONTAL_SCROLL
				| MainScreen.NO_HORIZONTAL_SCROLLBAR);
		
		init();
	}

	VerticalFieldManager vfm = null;
	LabelField lbl_status; 
	LabelField log;
	ButtonField cmdenviar;
	ButtonField cmdcancel;
	HorizontalFieldManager hfm;
	
	private void init() {

		Logger.getInstance().setILogger(this);
		
		// The background image.
		backgroundBitmap = Bitmap.getBitmapResource("img/title_sub_back.png");

		vfm = new VerticalFieldManager(VerticalFieldManager.NO_VERTICAL_SCROLL
				| VerticalFieldManager.NO_VERTICAL_SCROLLBAR
				| VerticalFieldManager.USE_ALL_WIDTH
				| VerticalFieldManager.NON_FOCUSABLE
				| VerticalFieldManager.USE_ALL_HEIGHT) {

			// Override the paint method to draw the background image.
			public void paint(Graphics graphics) {
				// Draw the background image and then call paint.
				graphics.drawBitmap(0, 0, Style.getScreenWidht(), 67, backgroundBitmap, 0, 0);
				super.paint(graphics);
			}
		};

		LabelField lbl_documento = new LabelField("Confirma el envio?",
				Field.FIELD_LEFT | Field.NON_FOCUSABLE);
		lbl_documento.setMargin(45, 25, 0, 25);
		vfm.add(lbl_documento);

		lbl_status = new LabelField(" ", Field.FIELD_LEFT
				| Field.NON_FOCUSABLE);
		lbl_status.setMargin(20, 12, 0, 12);
		
		vfm.add(lbl_status);
		
		//
		cmdenviar = new ButtonField("Enviar", ButtonField.FIELD_HCENTER);
		cmdenviar.setMargin(15,15,15,15);
		cmdenviar.setChangeListener(new FieldChangeListener() {
	
			public void fieldChanged(Field field, int context) {
				startSending();
			}
		});


		hfm = new HorizontalFieldManager(
				HorizontalFieldManager.NO_VERTICAL_SCROLL | HorizontalFieldManager.NO_VERTICAL_SCROLLBAR |
				HorizontalFieldManager.NO_HORIZONTAL_SCROLL | HorizontalFieldManager.NO_HORIZONTAL_SCROLLBAR | 
				HorizontalFieldManager.USE_ALL_WIDTH| HorizontalFieldManager.NON_FOCUSABLE );
		hfm.setMargin(20,0,0,0);
		hfm.add(cmdenviar);

		vfm.add(hfm);
		
		//
		cmdcancel = new ButtonField("Cancelar", ButtonField.FIELD_HCENTER);
		cmdcancel.setMargin(15,15,15,15);
		cmdcancel.setChangeListener(new FieldChangeListener() {
			
			public void fieldChanged(Field field, int context) {
				
				int i = Dialog.ask( Dialog.D_YES_NO, "Desea cancelar el envio de su reclamo?" , Dialog.NO);
		
				if(i == Dialog.YES){
					killSend();
					
					Screen screen = ScreenFlow.getInstance().getNext("cancel");
					UiApplication.getUiApplication().pushScreen(screen);
					try {
						UiApplication.getUiApplication().popScreen(
								ScreenFlow.getInstance().getSENDING_PAGE());
					} catch (IllegalArgumentException e) {
					}
				} 
			}
		});
	
		log = new LabelField(" " , Field.FIELD_LEFT | Field.NON_FOCUSABLE);
		vfm.add(log);
		// Add the manager to the screen.
		add(vfm);
		
		//inDebug?
		InfoService service = new InfoService();
		Integer k = new Integer(1);
		Info o = service.getByKey(k);
		if(o == null){
			throw new RuntimeException("Aun no se ha cargado la informacion personal");
		}
	}
	
	String llog; 
	public void log(String text){

		if(!true){
			//llog = text + "\n" + llog;
			llog = llog + "\n" + text;
			UiApplication.getUiApplication().invokeLater(new Runnable() {
				public void run() {
					log.setText(llog);
				}
			});
		}
	}
	
	String lstatus; 
	public void status(String text){
		lstatus = text ;
		UiApplication.getUiApplication().invokeLater(new Runnable() {
			public void run() {
				lbl_status.setText(lstatus);
			}
		});
		
	}
	
	
	//
	SendingScreen me = null;
	boolean reintentar = true; 
	public void startSending(){
		//
		hfm.delete(cmdenviar);

		me = this;
		//
		UiApplication.getUiApplication().invokeLater(new Runnable() {
			public void run() {
				try {
					status("Enviando datos...");

					if(reintentar){
						hfm.add(cmdcancel);
						reintentar = false;
					}

					SendReclamoCommand runnable = new SendReclamoCommand();
					runnable.setSendingScreen(me);

					
					sendingThread = new Thread( runnable );
					sendingThread.start();
				} catch(Exception e){
					reintentar(true);
				}
			}
		});
	}
		
	public void reintentar(boolean serviceFailed){
		if(serviceFailed){
			UiApplication.getUiApplication().invokeLater(new Runnable() {
				public void run() {
					status("Servicio no disponible en este momento. Reintente mas tarde.");
					hfm.add(cmdenviar);
					cmdenviar.setLabel("Reintentar");
				}
			});
		} else {
			UiApplication.getUiApplication().invokeLater(new Runnable() {
				public void run() {
					status("Error de comunicacion con el servicio.");
					hfm.add(cmdenviar);
					cmdenviar.setLabel("Reintentar");
				}
			});
		}
	}
	
	Thread sendingThread = null;
	
	public void killSend()
	{
		status("Envio cancelado.");

		if(sendingThread != null){
			try {
				sendingThread.interrupt();
			} catch(Exception ex){
				
			}
		}
		try {
			//
			setDirty(false);
			super.close();
		} catch(Exception ex){
			
		}
	}
	
	
	public void messageSent() {
		UiApplication.getUiApplication().invokeLater(new Runnable() {
			public void run() {
				Screen screen = ScreenFlow.getInstance().getNext("success");
				UiApplication.getUiApplication().pushScreen(screen);
				try {
					UiApplication.getUiApplication().popScreen(
							ScreenFlow.getInstance().getSENDING_PAGE());
				} catch (IllegalArgumentException e) {
				}
			}
		});
	}
	
	public void cancelSession() {
		
		Screen screen = ScreenFlow.getInstance().getNext("cancel");
		UiApplication.getUiApplication().pushScreen(screen);
		try {
			UiApplication.getUiApplication().popScreen(
					ScreenFlow.getInstance().getSENDING_PAGE());
		} catch (IllegalArgumentException e) {
		}
	}
	
	

	protected boolean invokeAction(int action) {
		boolean handled = super.invokeAction(action);

		if (!handled) {
			switch (action) {
				case ACTION_INVOKE: // Trackball click.
				{
					return true;
				}
			}
		}
		return handled;
	}
	
	public void close() {
		this.setDirty(false);
		super.close();
	}

	//
	public void callback(int event, Object parameters) {
		
		if(event == CommandCallback.END_RUN){
			this.messageSent();
		}
		
		if(event == CommandCallback.FAIL_RUN){
			if(parameters != null){
				boolean serviceFailed = parameters.toString().equalsIgnoreCase("true");
				this.reintentar(serviceFailed);
			} else {
				this.reintentar(true);
			}
		}
	}
	
}

